package com.pororo.smartoff;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SmartOffActivity extends Activity {
	TextView textService;
	TextView textTime;
	CheckBox chkService;
	LinearLayout layout_Db_init;

	SmartOffAdmin mAdmin;

	ArrayList<AppInfo> appList;
	CustomAdapter customAdapter;
	ListView listView;
	int total;
	
	final static String TAG = "SmartOffActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		SmartOffPreferences.setPreferences(this);

		textService = (TextView) this.findViewById(R.id.text_service);
		textTime = (TextView) this.findViewById(R.id.text_total_time);
		chkService = (CheckBox) this.findViewById(R.id.checkbox_service);
		listView = (ListView) this.findViewById(R.id.listview_app);

		layout_Db_init = (LinearLayout) this.findViewById(R.id.layout_db_init);
		appList = new ArrayList<AppInfo>();
		customAdapter = new CustomAdapter(this.getLayoutInflater());
		listView.setAdapter(customAdapter);

		chkService.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				DevicePolicyManager mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
				ComponentName mComponent = new ComponentName(
						SmartOffActivity.this, SmartOffAdmin.class);
				boolean mAdminActive;
				mAdminActive = mDPM.isAdminActive(mComponent);

				if (!mAdminActive) {
					Intent intent = new Intent(
							DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
					intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
							mComponent);
					intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
							"get device policy service");
					startActivityForResult(intent, 0);
				} else if (SmartOffPreferences.getBoolean("ServiceStatus") == false) {
					Log.v(TAG, "ServiceStatus = false");
					SmartOffPreferences.setBoolean("ServiceStatus", true);
					chkService.setChecked(true);
					Intent intent = new Intent(SmartOffActivity.this,
							SmartOffRegisterService.class);
					SmartOffPreferences.setBoolean("SaveTopPackage", true);
					startService(intent);
				} else {
					Log.v(TAG, "ServiceStatus = true");
					SmartOffPreferences.setBoolean("ServiceStatus", false);
					chkService.setChecked(false);
					Intent intent = new Intent(SmartOffActivity.this,
							SmartOffRegisterService.class);
					stopService(intent);
				}
			}
		});
		

		layout_Db_init.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				Builder dlg = new AlertDialog.Builder(SmartOffActivity.this);

				dlg.setTitle("초기화")
				.setMessage("초기화를 시키겠습니까?")
				.setIcon(R.drawable.ic_launcher)
				.setPositiveButton("아니오",
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int which) {
					}

				})
				.setNegativeButton("예",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int which) {
						SmartOffDBHelper.updateAppCountZero(getApplicationContext());
						appList = new ArrayList<AppInfo>();
						customAdapter.notifyDataSetChanged();
						textTime.setText("");
					}

				}).show();

			}
		});
		
		layout_Db_init.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch(event.getAction()) {
				case MotionEvent.ACTION_DOWN :
				case MotionEvent.ACTION_MOVE :
					layout_Db_init.setBackgroundColor(0xff80ceea);
					break;
				case MotionEvent.ACTION_UP :
					layout_Db_init.setBackgroundColor(Color.TRANSPARENT);
					break;
				}
				return false;
			}
		});

		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long flags) {
				Intent intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				Uri uri = Uri.fromParts("package", appList.get(position).getName(), null);
				intent.setData(uri);
				
				startActivity(intent);
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.i(TAG, "onResume");
		appList = SmartOffDBHelper.selectAppInfo(this);
		setAppListPercent();
		customAdapter.notifyDataSetChanged();
		
		textTime.setText("총 "+getTimeString(total));

		boolean serviceStatus = checkRunningService("com.pororo.smartoff.SmartOffRegisterService");
		SmartOffPreferences.setBoolean("ServiceStatus", serviceStatus);
		chkService.setChecked(serviceStatus);
	}

	public void setAppListPercent() {
		if (appList != null) {
			total = 0;

			for (AppInfo appInfo : appList) {
				total += appInfo.getTime();
			}

			for (int i = 0; i < appList.size(); i++) {
				appList.get(i).setPercent(
						(appList.get(i).getTime() * 100) / total);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) {
		case Activity.RESULT_OK:
			Log.v(TAG, "onActivityResult : Activity.RESULT_OK");
			Intent intent = new Intent(SmartOffActivity.this,
					SmartOffRegisterService.class);
			SmartOffPreferences.setBoolean("ServiceStatus", true);
			chkService.setChecked(true);
			SmartOffPreferences.setBoolean("SaveTopPackage", true);
			startService(intent);
			break;
		case Activity.RESULT_CANCELED:
			Log.v(TAG, "onActivityResult : Activity.RESULT_Cancel");
			SmartOffPreferences.setBoolean("ServiceStatus", false);
			chkService.setChecked(false);
			break;
		}
	}

	public boolean checkRunningService(String serviceName) {
		ActivityManager activityManater = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> list = activityManater
				.getRunningServices(Integer.MAX_VALUE);

		for (RunningServiceInfo info : list) {
			// Test
			// Log.d(TAG, "Service : " + info.service.getClassName());
			if (info.service.getClassName().equals(serviceName)) {
				return true;
			}
		}
		return false;
	}

	public Drawable getIconWithPackageName(String packageName) {
		// Return Drawable icon with Package Name
		PackageManager packgageManager = getPackageManager();
		Drawable icon = null;

		try {
			icon = packgageManager.getApplicationIcon(packageName);
		} catch (NameNotFoundException e) {
			icon = null;
			e.printStackTrace();
		}

		return icon;
	}

	public String getApplicationNameWithPackageName(String packageName) {
		// Return Application Name with Package Name
		PackageManager packageManager = getPackageManager();
		String applicationName = null;

		try {
			applicationName = (String) packageManager
					.getApplicationLabel(packageManager.getApplicationInfo(
							packageName, 0));
		} catch (NameNotFoundException e) {
			applicationName = "(Unknown)";
			e.printStackTrace();
		}

		return applicationName;
	}

	public class CustomAdapter extends BaseAdapter {
		LayoutInflater inflater;

		public CustomAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return appList.size();
		}

		@Override
		public Object getItem(int position) {
			return appList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.custom_row, null);
			}

			ImageView imageView = (ImageView) convertView
					.findViewById(R.id.image_icon);
			TextView appName = (TextView) convertView
					.findViewById(R.id.text_name);
			TextView percent = (TextView) convertView
					.findViewById(R.id.text_percent);
			TextView timeInfo = (TextView) convertView
					.findViewById(R.id.text_time);
			ProgressBar progress = (ProgressBar) convertView
					.findViewById(R.id.progress_percent);

			AppInfo appInfo = appList.get(position);

			imageView
					.setImageDrawable(getIconWithPackageName(appInfo.getName()));
			appName.setText(getApplicationNameWithPackageName(appInfo.getName()));
			percent.setText(appInfo.getPercent() + "%");
			progress.setProgress(appInfo.getPercent());

			int time = appInfo.getTime();
			timeInfo.setText(getTimeString(time));
			return convertView;
		}

	}

	public String getTimeString(int inputTime) {
		String timeStr = "";
		if ( inputTime > 3600 ) {
			timeStr += inputTime/3600 + " 시간 ";
			inputTime %= 3600;
		} 
		
		if ( inputTime > 60 ) {
			timeStr += inputTime/60 + " 분 ";
			inputTime %= 60;
		}
		
		timeStr += inputTime + " 초";
		return timeStr;
	}
}
